import hashlib

from django.http import HttpResponseRedirect
from django.shortcuts import render

from login.models import *


# Create your views here.
def login(request):
    if request.method == "GET":
        return render(request, 'login/login.html')
    elif request.method == "POST":
        name = request.POST['name']
        pswd = request.POST['pswd']
        # 哈希算法
        m = hashlib.md5()
        m.update(pswd.encode())
        pswd_m = m.hexdigest()
        try:
            user = User.objects.filter(name=name, pswd=pswd_m)
        except Exception as e:
            print("login:", e)
        if user:
            user = User.objects.get(name=name)
            request.session['name'] = user.name
            return HttpResponseRedirect('/user/')
        else:
            msg = "账号或密码错误！！！"
            return render(request, 'login/login.html', {"msg": msg})


def register(request):
    if request.method == "GET":
        return render(request, 'login/register.html')
    if request.method == "POST":
        name = request.POST['name']
        pswd_1 = request.POST['pswd_1']
        pswd_2 = request.POST['pswd_2']
        if pswd_1 != pswd_2:
            msg = "密码不一致！"
            return render(request, "login/register.html", {"msg": msg})
        try:
            user = User.objects.filter(name=name, is_active=True)
        except Exception as e:
            print("register:", e)
        if user:
            msg = "用户名已存在！"
            return render(request, 'login/register.html', {"msg": msg})
        # 哈希算法
        m = hashlib.md5()
        m.update(pswd_2.encode())
        pswd_m = m.hexdigest()
        # print(pswd_m)
        try:
            user = User.objects.create(name=name, pswd=pswd_m)
        except Exception as e:
            print("register_create_user:", e)
        if user:
            msg = "注册成功！"
            return render(request, 'login/login.html', {"msg": msg})
        msg = "注册失败！！"
        return render(request, 'login/register.html', {"msg": msg})


def logout(request):
    if 'name' in request.session:
        del request.session['name']
    return HttpResponseRedirect('/')


def pasword_edit(request):
    name = request.session.get('name')
    try:
        user = User.objects.filter(name=name)
    except Exception as e:
        print(e)

    if request.method == 'GET':
        return render(request, 'login/password_edit.html')
    if request.method == 'POST':

        pswd1 = request.POST['pswd1']
        pswd2 = request.POST['pswd2']

        # 哈希算法
        m = hashlib.md5()
        m.update(pswd1.encode())
        pswd1 = m.hexdigest()

        if pswd1 == user.get().pswd:
            # 哈希算法
            m = hashlib.md5()
            m.update(pswd2.encode())
            pswd2 = m.hexdigest()

            user.update(pswd=pswd2)
            return HttpResponseRedirect('/logout/')
        else:
            msg = "密码错误"
            return render(request, 'login/password_edit.html', {"msg": msg})
